import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getProducts, getModules, getModuleDetails, getDashboardData } from '@/api/modules'

export const useModulesStore = defineStore('modules', () => {
  // 状态
  const products = ref([])
  const modules = ref([])
  const currentProduct = ref(null)
  const currentVersion = ref(null)
  const loading = ref(false)
  const error = ref(null)
  const dashboardData = ref(null)

  // 计算属性
  const hasProducts = computed(() => products.value.length > 0)
  const hasModules = computed(() => modules.value.length > 0)
  const currentProductName = computed(() => {
    if (!currentProduct.value || !products.value.length) return ''
    const product = products.value.find(p => p.name === currentProduct.value)
    return product ? product.displayName : currentProduct.value
  })

  // 方法
  const fetchProducts = async () => {
    loading.value = true
    error.value = null
    try {
      const response = await getProducts()
      // 处理后端返回的数据格式：[["0","macOS","x86_12.5","deps","modules","records","symbols"]]
      const rawData = response.data || []
      products.value = rawData.map(item => ({
        id: item[0],
        name: item[1],
        version: item[2],
        displayName: `${item[1]} ${item[2]}`
      }))

      // 自动选择第一个产品
      if (products.value.length > 0) {
        const firstProduct = products.value[0]
        currentProduct.value = firstProduct.name
        currentVersion.value = firstProduct.version
      }
    } catch (err) {
      error.value = err.message || '获取产品列表失败'
      console.error('获取产品列表失败:', err)
    } finally {
      loading.value = false
    }
  }

  const fetchModules = async () => {
    if (!currentProduct.value || !currentVersion.value) {
      error.value = '请先选择产品版本'
      return
    }

    loading.value = true
    error.value = null
    try {
      const response = await getModules(currentProduct.value, currentVersion.value)
      // 处理后端返回的模块数据格式
      const rawData = response.data || []
      modules.value = rawData.map(item => ({
        id: item[0],
        name: item[2] || 'Unknown',
        path: item[1] || '',
        dependencies: parseInt(item[3]) || 0,
        symbols: parseInt(item[4]) || 0,
        records: parseInt(item[5]) || 0,
        size: parseInt(item[8]) || 0,
        complexity: Math.min(100, Math.floor(Math.random() * 80) + 20), // 模拟复杂度
        memoryUsage: parseInt(item[13]) || 0,
        pss: parseInt(item[13]) || 0, // 添加PSS字段支持
        riskLevel: '低', // 默认风险等级
        dependedBy: 0, // 初始化被依赖数，稍后计算
        procesess: '' // 初始化进程信息，稍后填充
      }))

    // 计算每个模块的被依赖数
    const moduleMap = {}
    modules.value.forEach(module => {
      moduleMap[module.name] = module
    })

    // 统计每个模块被其他模块依赖的次数，并模拟进程信息
    modules.value.forEach(module => {
      // 这里我们简化处理，使用模块名来判断依赖关系
      // 在实际应用中，可能需要更复杂的依赖关系数据
      const dependentCount = Math.floor(Math.random() * 30) + 1 // 模拟被依赖数
      module.dependedBy = dependentCount

      // 模拟进程信息，基于后台日志中观察到的模式
      const processCount = Math.floor(Math.random() * 15) + 1 // 1-15个进程
      const processNames = [
        'kernel', 'launchd', 'WindowServer', 'usernoted', 'configd',
        'syslogd', 'mDNSResponder', 'airportd', 'powerd', 'thermalmonitord',
        'logd', 'apsd', 'cfprefsd', 'distnoted', 'coreduetd'
      ]

      const selectedProcesses = processNames
        .sort(() => 0.5 - Math.random())
        .slice(0, processCount)
        .join(',')

      module.procesess = selectedProcesses
    })
    } catch (err) {
      error.value = err.message || '获取模块列表失败'
      console.error('获取模块列表失败:', err)
    } finally {
      loading.value = false
    }
  }

  const setProduct = (product, version) => {
    currentProduct.value = product
    currentVersion.value = version
    modules.value = [] // 清空模块列表，重新加载
  }

  const fetchModuleDetails = async (moduleId) => {
    try {
      const response = await getModuleDetails(currentProduct.value, currentVersion.value, moduleId)
      return response.data
    } catch (err) {
      error.value = err.message || '获取模块详情失败'
      console.error('获取模块详情失败:', err)
      throw err
    }
  }

  const fetchDashboardData = async () => {
    if (!currentProduct.value || !currentVersion.value) {
      error.value = '请先选择产品版本'
      return null
    }

    try {
      const response = await getDashboardData(currentProduct.value, currentVersion.value)
      dashboardData.value = response.data
      return response.data
    } catch (err) {
      error.value = err.message || '获取仪表板数据失败'
      console.error('获取仪表板数据失败:', err)
      return null
    }
  }

  // 初始化
  const initialize = async () => {
    await fetchProducts()
    if (currentProduct.value && currentVersion.value) {
      await fetchModules()
      await fetchDashboardData()
    }
  }

  return {
    // 状态
    products,
    modules,
    currentProduct,
    currentVersion,
    loading,
    error,
    dashboardData,

    // 计算属性
    hasProducts,
    hasModules,
    currentProductName,

    // 方法
    fetchProducts,
    fetchModules,
    fetchModuleDetails,
    fetchDashboardData,
    setProduct,
    initialize
  }
})